package com.example.statistics.common

import android.os.Bundle
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import com.example.statistics.R
import com.example.statistics.common.BaseActivity
import com.google.android.material.tabs.TabLayout
import kotlinx.android.synthetic.main.activity_base_fragment.*

abstract class BaseFragmentActivity : BaseActivity() {

    var currentIndex = 0

    var fragmentList: List<Pair<androidx.fragment.app.Fragment, String>> = listOf()
        set(value) {
            field = value
            tab_layout
            tab_layout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
                override fun onTabReselected(p0: TabLayout.Tab?) {
                    onTabSelected(p0)
                }

                override fun onTabUnselected(p0: TabLayout.Tab?) {

                }

                override fun onTabSelected(p0: TabLayout.Tab?) {
                    currentIndex = p0?.position ?: currentIndex
                }
            })


            view_pager.offscreenPageLimit = 1
            view_pager.adapter = TabPageAdapter(supportFragmentManager)
            tab_layout.setupWithViewPager(view_pager)
        }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_base_fragment)
    }


    inner class TabPageAdapter(fragmentManager: androidx.fragment.app.FragmentManager) : FragmentStatePagerAdapter(fragmentManager) {
        override fun getItem(p0: Int): androidx.fragment.app.Fragment {
            return fragmentList[p0].first
        }

        override fun getCount(): Int {
            return fragmentList.size
        }

        override fun getPageTitle(position: Int): CharSequence? {
            return fragmentList[position].second
        }

        override fun getItemPosition(`object`: Any): Int {
            return POSITION_NONE
        }
        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            var f = super.instantiateItem(container, position) as Fragment
            val tag = f.tag
            if (f != getItem(position)) {
                val ft = f.childFragmentManager.beginTransaction()
                ft.remove(f)
                f = getItem(position)
                ft.add(container.id, f, tag)
                ft.attach(f)
                ft.commitAllowingStateLoss()
            }
            return f
        }
    }
}